﻿
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using VOL.Core.Configuration;
using VOL.Core.Controllers.Basic;
using VOL.Core.DBManager;
using VOL.Core.EFDbContext;
using VOL.Core.Enums;
using VOL.Core.Extensions;
using VOL.Core.Filters;
using VOL.Core.Infrastructure;
using VOL.Core.ManageUser;
using VOL.Core.ObjectActionValidator;
using VOL.Core.UserManager;
using VOL.Core.Utilities;
using VOL.Entity.AttributeManager;
using VOL.Entity.DomainModels;
using VOL.System.IRepositories;
using VOL.System.IServices;
using VOL.System.Repositories;

namespace VOL.System.Controllers
{
    [Route("api/User")]
    public partial class Sys_UserController
    {

        private ISys_UserService _userService;
        private ISys_RoleRepository _roleRepository;
        private ISys_UserRoleRepository _userRepository;
        private WebResponseContent _webResponse;
        /// <summary>
        /// 2020.11.28
        /// </summary>
        /// <param name="userService"></param>
        /// <param name="roleRepository"></param>
        /// <param name="userRepository"></param>
        [ActivatorUtilitiesConstructor]
        public Sys_UserController(
            ISys_UserService userService,
            ISys_RoleRepository roleRepository,
            ISys_UserRoleRepository userRepository)
            : base(userService)
        {
            _userService = userService;
            _roleRepository = roleRepository;
            _userRepository = userRepository;
            _webResponse = new WebResponseContent();
        }

        /// <summary>
        /// 用户管理设置角色(获取所有角色)2020.11.28
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("getRoles"), ApiActionPermission(ActionPermissionOptions.Search)]
        public IActionResult GetRoles()
        {
            //var roles = await _roleRepository.FindAsIQueryable(x => true)
            // .OrderByDescending(x => x.OrderNo)
            // .Select(s => new { roleId = s.Role_Id, s.RoleName })
            // .ToListAsync();
            return Json(RoleContext.GetAllChildren(UserContext.Current.RoleId));
        }

        /// <summary>
        /// 用户管理设置角色(获取所有角色)2020.11.28
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("getUserRoles"), ApiActionPermission(ActionPermissionOptions.Search)]
        public async Task<IActionResult> GetUserRoles(int userId)
        {
            var roles = await _userRepository.FindAsIQueryable(x => x.UserId == userId && x.Enable == 1)
              .Select(s => s.RoleId)
              .ToListAsync();
            return Json(roles);
        }

        /// <summary>
        /// 保存用户角色2020.11.28
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("saveRole"), ApiActionPermission(ActionPermissionOptions.Update)]
        public async Task<IActionResult> SaveRole([FromBody] int[] roleIds, int userId)
        {
            if (roleIds == null || userId <= 0)
            {
                return Json(_webResponse.OK("未获取到参数"));
            }

            //如果需要判断当前角色是否越权，再调用一下获取当前角色下的所有子角色判断即可

            var roles = await _userRepository.FindAsIQueryable(x => x.UserId == userId)
              .Select(s => new { s.RoleId, s.Enable, s.Id })
              .ToListAsync();
            //没有设置角色
            if (roleIds.Length == 0 && roles.Exists(x => x.Enable == 1))
            {
                return Json(_webResponse.OK("保存成功"));
            }

            UserInfo user = UserContext.Current.UserInfo;
            //新设置的角色 
            var add = roleIds.Where(x => !roles.Exists(r => r.RoleId == x)).Select(s => new Sys_UserRole()
            {
                RoleId = s,
                UserId = userId,
                Enable = 1,
                CreateDate = DateTime.Now,
                Creator = user.UserTrueName,
                CreateID = user.User_Id
            }).ToList();

            //删除的角色 
            var update = roles.Where(x => !roleIds.Contains(x.RoleId) && x.Enable == 1).Select(s => new Sys_UserRole()
            {
                Id = s.Id,
                Enable = 0,
                ModifyDate = DateTime.Now,
                Modifier = user.UserTrueName,
                ModifyID = user.User_Id
            }).ToList();

            //之前设置过的角色重新分配 
            update.AddRange(roles.Where(x => roleIds.Contains(x.RoleId) && x.Enable != 1).Select(s => new Sys_UserRole()
            {
                Id = s.Id,
                Enable = 1,
                ModifyDate = DateTime.Now,
                Modifier = user.UserTrueName,
                ModifyID = user.User_Id
            }).ToList());
            _userRepository.AddRange(add);

            _userRepository.UpdateRange(update, x => new { x.Enable, x.ModifyDate, x.Modifier, x.ModifyID });
            await _userRepository.SaveChangesAsync();
            return Json(_webResponse.OK("保存成功"));
        }


        [HttpPost, HttpGet, Route("login"), AllowAnonymous]
        [ObjectModelValidatorFilter(ValidatorModel.Login)]
        public async Task<IActionResult> Login([FromBody] LoginInfo loginInfo)
        {
            return Json(await Service.Login(loginInfo));
        }

        [HttpPost, Route("replaceToken"), AllowAnonymous]
        public async Task<IActionResult> ReplaceToken()
        {
            return Json(await Service.ReplaceToken());
        }

        [HttpPost, Route("modifyPwd")]
        [ApiActionPermission]
        //通过ObjectGeneralValidatorFilter校验参数，不再需要if esle判断OldPwd与NewPwd参数
        [ObjectGeneralValidatorFilter(ValidatorGeneral.OldPwd, ValidatorGeneral.NewPwd)]
        public async Task<IActionResult> ModifyPwd(string oldPwd, string newPwd)
        {
            return Json(await Service.ModifyPwd(oldPwd, newPwd));
        }

        [HttpPost, Route("getCurrentUserInfo")]
        public async Task<IActionResult> GetCurrentUserInfo()
        {
            return Json(await Service.GetCurrentUserInfo());
        }

        //只能超级管理员才能修改密码
        //2020.08.01增加修改密码功能
        [HttpPost, Route("modifyUserPwd"), ApiActionPermission(ActionRolePermission.SuperAdmin)]
        public IActionResult ModifyUserPwd(string password, string userName)
        {
            WebResponseContent webResponse = new WebResponseContent();
            if (string.IsNullOrEmpty(password) || string.IsNullOrEmpty(userName))
            {
                return Json(webResponse.Error("参数不完整"));
            }
            if (password.Length < 6) return Json(webResponse.Error("密码长度不能少于6位"));

            ISys_UserRepository repository = Sys_UserRepository.Instance;
            Sys_User user = repository.FindFirst(x => x.UserName == userName);
            if (user == null)
            {
                return Json(webResponse.Error("用户不存在"));
            }
            user.UserPwd = password.EncryptDES(AppSetting.Secret.User);
            repository.Update(user, x => new { x.UserPwd }, true);
            //如果用户在线，强制下线
            UserContext.Current.LogOut(user.User_Id);
            return Json(webResponse.OK("密码修改成功"));
        }

        /// <summary>
        /// 2020.06.15增加登陆验证码
        /// </summary>
        /// <returns></returns>
        [HttpGet, Route("getVierificationCode"), AllowAnonymous]
        public IActionResult GetVierificationCode()
        {
            string code = VierificationCode.RandomText();
            var data = new
            {
                img = VierificationCode.CreateBase64Imgage(code),
                uuid = Guid.NewGuid()
            };
            HttpContext.GetService<IMemoryCache>().Set(data.uuid.ToString(), code, new TimeSpan(0, 5, 0));
            return Json(data);
        }
    }
}
